//
//  GameplayLayer2.m
//  SpaceViking
//
//  Created by gnt on 12/26/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "GameplayLayer2.h"

@implementation GameplayLayer2

float timeStartAction;
float timeGame;

- (void) dealloc{
    [guardButton release];
    [katana release];
    [labelHPBoss release];
    [labelHPPlayer release];
    [labelWinOrLose release];
    [slashSword release];
    CFRelease(map);
    [super dealloc];
}

-(void) update:(ccTime)deltaTime {
    timeGame += deltaTime;
    CCArray *listOfGameObjects = [enemyWaitingBatchNode children];
    Boss *boss = (Boss*)[self getChildByTag:kBossSpriteTagValue];
    PlayerScene2 *player = (PlayerScene2*)[self getChildByTag:kPlayerSpriteTagValue];
    
    if(boss.characterHealth > 0 && player.healthOfPlayer > 0){
        // process render katana
        [self processKatana];
    
        // process render SlashSword
        [self processSlashSword];
    
        // process Boss Slashing
        Boolean isBossTakeAHit = [self processBossSlashing];
    
        // process Player Slashing
        [self processPlayerSlashing:isBossTakeAHit];    
    
        [boss updateStateWithDeltaTime:deltaTime andListOfGameObjects:listOfGameObjects];
        [labelHPBoss setString:[NSString stringWithFormat:@"%i / 20",boss.characterHealth]];
        [labelHPPlayer setString:[NSString stringWithFormat:@"%i / 20",player.healthOfPlayer]];
        deltaX = 0;
        deltaY = 0;
    }else if(boss.characterHealth <= 0 && [boss numberOfRunningActions] == 0){
        [boss changeState:kStateDead];
        [boss updateStateWithDeltaTime:deltaTime andListOfGameObjects:listOfGameObjects];
        labelWinOrLose = [CCLabelTTF labelWithString:@"WIN" fontName:@"Arial" fontSize:80];
        labelWinOrLose.position = ccp(512, 600);
        [self addChild:labelWinOrLose z:100];
        //[self stopAllActions];
    }else if (player.healthOfPlayer <= 0){
        labelWinOrLose = [CCLabelTTF labelWithString:@"LOSE" fontName:@"Arial" fontSize:80];
        labelWinOrLose.position = ccp(512, 600);
        [self addChild:labelWinOrLose z:100];
        [self stopAllActions];
    }
}

- (void) processKatana{
    PlayerScene2 *player = (PlayerScene2*)[self getChildByTag:kPlayerSpriteTagValue];
    
    if(guardButton.active && guardButton.isHoldable ==1)
    {
        katana.visible = YES;
        player.boolDefendByGuardButton = true;
    }
    else
    {
        katana.visible = NO;
        player.boolDefendByGuardButton = false;
    }
}

- (void) processSlashSword{
    PlayerScene2 *player = (PlayerScene2*)[self getChildByTag:kPlayerSpriteTagValue];
    
    if(player.boolDefendByTouch && deltaX != 0 && deltaY != 0) {
        artan = (float)CC_RADIANS_TO_DEGREES(atan2f(deltaX, deltaY));
        CCLOG(@"artan = , %f",artan);
        slashSword.rotation = artan + 90;
        if(slashSword.visible == NO) {
            slashSword.visible = YES;
            timeStartAction = timeGame;
        }
    }
    if(slashSword.visible == YES)
    {
        if((timeGame - timeStartAction) > 1.f)
        {
            slashSword.visible = NO;
            timeGame = 0;
            timeStartAction = 0;
        }
    }

}

- (void)processPlayerSlashing:(Boolean) isBossTakeAHit{
    Boss *boss = (Boss*)[self getChildByTag:kBossSpriteTagValue];

    if(deltaX != 0 && deltaY != 0 && isBossTakeAHit == YES && slashSword.visible == YES && boss.characterState != kStateDefend){
        [boss setCharacterHealth:boss.characterHealth - 1];
    }
}

- (Boolean)processBossSlashing{
    Boolean isBossTakeAHit = YES;
    Boss *boss = (Boss*)[self getChildByTag:kBossSpriteTagValue];
    PlayerScene2 *player = (PlayerScene2*)[self getChildByTag:kPlayerSpriteTagValue];
    
    if(!player.boolDefendByGuardButton) {
        // player is slashing defend
        if (boss.characterState == kStateSlashBegin && ((artan >= -10 && artan <= -1) || (artan >= 1 && artan <= 10))) {
            [boss changeState:kStateTakingDamage];
            isBossTakeAHit = NO;
            //reset artan default
            artan = 190;
        }
        else if(boss.characterState == kStateSlashLeft && ((artan >= -100 && artan <= -80))){
            [boss changeState:kStateTakingDamage];
            isBossTakeAHit = NO;
            //reset artan default
            artan = 190;
        }
        else if(boss.characterState == kStateSlashLeftTop && ((artan >= -55 && artan <= -35))){
            [boss changeState:kStateTakingDamage];
            isBossTakeAHit = NO;
            //reset artan default
            artan = 190;
        }
        else if(boss.characterState == kStateSlashRightTop && ((artan >= 35 && artan <= 55))){
            [boss changeState:kStateTakingDamage];
            isBossTakeAHit = NO;
            //reset artan default
            artan = 190;
        }
        else if(boss.characterState == kStateSlashRight && ((artan >= 80 && artan <= 100))){
            [boss changeState:kStateTakingDamage];
            isBossTakeAHit = NO;
            //reset artan default
            artan = 190;
        }
        else{
            // khac phuc slash thuong co 3 action nen tru 3 lan
            // them action them condition vao the if nay
            //isBossTakeAHit = YES;
            if([boss numberOfRunningActions] == 0 && (boss.characterState == kStateSlashBegin || boss.characterState == kStateSlashLeft || boss.characterState == kStateSlashLeftTop || boss.characterState == kStateSlashRightTop || boss.characterState == kStateSlashRight)){
                [player setHealthOfPlayer:player.healthOfPlayer -1]; 
            }
            
        }
    }
    return isBossTakeAHit;
}

- (void)initGuardButton {
    //CGSize screenSize = [CCDirector sharedDirector].winSize;
    CGRect guardButtonDimensions = CGRectMake(0, 0, 125, 150);
    CGPoint guardButtonPosition = ccp(60, 60);
    // chua dinh lai kich thuoc cho cac loai man hinh 3gs, ipad, i4
    
    SneakyButtonSkinnedBase *guardButtonBase = [[[SneakyButtonSkinnedBase alloc]init]autorelease];
    guardButtonBase.position = guardButtonPosition;
    guardButtonBase.defaultSprite = [CCSprite spriteWithFile:@"guard1.png"];
    guardButtonBase.activatedSprite = [CCSprite spriteWithFile:@"guard2.png"];
    guardButtonBase.pressSprite = [CCSprite spriteWithFile:@"guard2.png"];
    guardButtonBase.button = [[SneakyButton alloc]initWithRect:guardButtonDimensions];
    guardButton = [guardButtonBase.button retain];
    guardButton.isToggleable = NO;
    guardButton.isHoldable = YES;
    [self addChild:guardButtonBase];
}

- (id)init {
    if((self = [super init]))
    {
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            [[CCSpriteFrameCache sharedSpriteFrameCache] 
             addSpriteFramesWithFile:@"wait.plist"];
            [[CCSpriteFrameCache sharedSpriteFrameCache] 
             addSpriteFramesWithFile:@"slash.plist"];
            [[CCSpriteFrameCache sharedSpriteFrameCache] 
             addSpriteFramesWithFile:@"takeAHit.plist"];
            [[CCSpriteFrameCache sharedSpriteFrameCache] 
             addSpriteFramesWithFile:@"enemyDying.plist"];
            [[CCSpriteFrameCache sharedSpriteFrameCache] 
             addSpriteFramesWithFile:@"defend.plist"];
            [[CCSpriteFrameCache sharedSpriteFrameCache] 
             addSpriteFramesWithFile:@"slashingLeft.plist"];
            [[CCSpriteFrameCache sharedSpriteFrameCache] 
             addSpriteFramesWithFile:@"enemy_slash1.plist"];
            [[CCSpriteFrameCache sharedSpriteFrameCache] 
             addSpriteFramesWithFile:@"enemy_slash2.plist"];
            [[CCSpriteFrameCache sharedSpriteFrameCache] 
             addSpriteFramesWithFile:@"slashingLeftTop.plist"];
            [[CCSpriteFrameCache sharedSpriteFrameCache] 
             addSpriteFramesWithFile:@"slashingRightTop.plist"];
            [[CCSpriteFrameCache sharedSpriteFrameCache] 
             addSpriteFramesWithFile:@"slashingRight.plist"];

//            enemyWaitingBatchNode = [CCSpriteBatchNode 
//                                    batchNodeWithFile:@"wait.png"];
//            [self addChild:enemyWaitingBatchNode z:-1];            
        } else {
            //not support iphone
        }
        
        
    }
    CGSize screenSize = [CCDirector sharedDirector].winSize;
    [self initGuardButton];
    isTouchEnabled_ =1;
    map = CFDictionaryCreateMutable(NULL,0,NULL,NULL);
    Boss *boss = [[Boss alloc]init];
    [self addChild:boss z:kBossSpriteZValue tag:kBossSpriteTagValue];
    // add playerScene2
    PlayerScene2 *player = [[PlayerScene2 alloc] init];
    [self addChild:player z:kPlayerSpriteZValue tag:kPlayerSpriteTagValue];
    
    // init katana
    katana = [CCSprite spriteWithFile:@"katana.png"];
    CGSize sizeKatana = [katana contentSize];
    katana.position = ccp(screenSize.width - (sizeKatana.width/2), screenSize.height/4);
    katana.visible = NO;
    [self addChild:katana z:kPlayerSpriteZValue];
    [self scheduleUpdate];  
    
    // add Label HP for Boss & Player
    labelHPBoss = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%i/ 20",boss.characterHealth] 
                                                 fontName:@"Arial" fontSize:60];
    labelHPBoss.position = ccp(900, 700);
    [self addChild:labelHPBoss];
    
    labelHPPlayer = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%i/ 20",player.healthOfPlayer] 
                                     fontName:@"Arial" fontSize:60];
    labelHPPlayer.position = ccp(100, 700);
    [self addChild:labelHPPlayer];
    
    // add label win or lose
    labelWinOrLose = [CCLabelTTF labelWithString:@"" fontName:@"Arial" fontSize:60];
    labelWinOrLose.position = ccp(screenSize.width/2, screenSize.height/2);
    //labelWinOrLose.visible = NO;
    //[self addChild:labelWinOrLose];
    
    // init image slash of katana
    slashSword = [CCSprite spriteWithFile:@"slashSword.png"];
    slashSword.position = ccp(screenSize.width/2, screenSize.height/4);
    slashSword.visible = NO;
    [self addChild:slashSword z:kSlashSwordZValue];
    return self;
}

- (void) ccTouchesBegan:(NSSet *) touches withEvent:(UIEvent *) event{
	//for (UITouch *touch in touches) {
//		CCBlade *w = [CCBlade bladeWithMaximumPoint:50];
//        int rand = arc4random() % 3 + 1;
//		w.texture = [[CCTextureCache sharedTextureCache] addImage:[NSString stringWithFormat:@"streak%d.png",rand]];
//        
//        CFDictionaryAddValue(map,touch,w);
//        
//		[self addChild:w];
        UITouch *touch = [touches anyObject];
		CGPoint pos = [touch locationInView:touch.view];
		pos = [[CCDirector sharedDirector] convertToGL:pos];
//		[w push:pos];
        xDown = pos.x;
        yDown = pos.y;
        //CCLOG(@"%i - %i",xDown,yDown);
	//}
    PlayerScene2 *player = (PlayerScene2*)[self getChildByTag:kPlayerSpriteTagValue];
    player.boolDefendByTouch = true;
   
}

- (void) ccTouchesMoved:(NSSet *) touches withEvent:(UIEvent *) event{
	//for (UITouch *touch in touches) {
//		CCBlade *w = (CCBlade *)CFDictionaryGetValue(map, touch);
//		CGPoint pos = [touch locationInView:touch.view];
//		pos = [[CCDirector sharedDirector] convertToGL:pos];
//		[w push:pos];
	//}
}

- (void) ccTouchesEnded:(NSSet *) touches withEvent:(UIEvent *) event{
	//for (UITouch *touch in touches) {
//		CCBlade *w = (CCBlade *)CFDictionaryGetValue(map, touch);
//		[w dim:YES];
//        CFDictionaryRemoveValue(map,touch);
        UITouch *touch = [touches anyObject];
        CGPoint pos = [touch locationInView:touch.view];
		pos = [[CCDirector sharedDirector] convertToGL:pos];
        xUp = pos.x;
        yUp = pos.y;
    deltaX = xUp - xDown;
    deltaY = yUp - yDown;
        //CCLOG(@"%i - %i",xUp,yUp);
	//}
    PlayerScene2 *player = (PlayerScene2*)[self getChildByTag:kPlayerSpriteTagValue];
    player.boolDefendByTouch = true;
}

@end
